import re
import time
from datetime import datetime
import subprocess
import sys
from argparse import RawTextHelpFormatter
import argparse

HDC_COMMAND = "hdc"
def parse_log_file(file_path):
    log_pattern = re.compile(r'\[(?P<timestamp>.+?)\] (?P<sessionID>\S+) (?P<command>.+)')
    parsed_logs = []

    with open(file_path, 'r') as file:
        for line in file:
            match = log_pattern.match(line)
            if match:
                try:
                    log_info = match.groupdict()
                    log_info['timestamp'] = datetime.strptime(log_info['timestamp'], '%Y%m%d-%H%M%S%f')
                    parsed_logs.append(log_info)
                except ValueError as e:
                    print(f"Error parsing line: {line.strip()} - {e}")

    return parsed_logs

def execute_commands_by_session(parsed_logs, target_session):
    session_logs = [log for log in parsed_logs if log['sessionID'] == target_session]
    session_logs.sort(key=lambda x: x['timestamp'])  # 按时间戳排序

    try:
        subprocess.run([HDC_COMMAND, "kill", "server"], check=True) # 先kill掉server

        prev_time = None
        for idx, entry in enumerate(session_logs):
            current_time = entry['timestamp']
            if idx > 0 and prev_time is not None:
                time_interval = max((current_time - prev_time).total_seconds(), 0)
                time.sleep(time_interval)
            prev_time = current_time

            command_parts = [HDC_COMMAND] + entry['command'].split()
            print(f"Executing command: {' '.join(command_parts)}")
            subprocess.run(command_parts, check=True)
    except subprocess.CalledProcessError as e:
        print(f"Subprocess error occurred: {e}")
    except Exception as e:
        print(f"Unexpected error occurred: {e}")
def tool():
    if len(sys.argv) == 1:
        sys.argv.append('--help')

    parser = argparse.ArgumentParser(
        prog='HDC Command Reply Script',
        description='This script is used to parse and execute HDC commands based on log files.',
        epilog='For more information, please refer to the official documentation.',
    )

    parser.add_argument(
        '-t', '--targetSessionID', 
        type=str, 
        default='', 
        metavar='targetSessionID',
        help="Target session ID to execute commands for."
    )
    parser.add_argument(
        '-a', '--allSessions', 
        action='store_true', 
        help="Default parsing command for all session IDs in the log file."
    )

    arguments = parser.parse_args()
    return arguments

if __name__ == "__main__":
    arguments = tool()
    
    log_file_path = './hdc-cmd.log'

    if arguments.allSessions:
        parsed_logs = parse_log_file(log_file_path)
        
        unique_sessions = {log['sessionID'] for log in parsed_logs}

        for session_id in unique_sessions:
            execute_commands_by_session(parsed_logs, session_id)

    else:
        if not arguments.targetSessionID:
            print("Error: No target session ID provided. Use -t or --targetSessionID to specify a session ID.")
            sys.exit(1)

        parsed_logs = parse_log_file(log_file_path)
        execute_commands_by_session(parsed_logs, arguments.targetSessionID)

    # subprocess.run("hdc kill server", shell=True)  # 最后确保hdc server被关闭